/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.servlets;

import com.jmooc.entity.User;
import com.jmooc.service.UserService;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Group
 */
@WebServlet(name = "LoginServlet", urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {

    @EJB
    private UserService userService;
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String mail = req.getParameter("email");
        String password = req.getParameter("password");
        HttpSession session = req.getSession();
       
        if (userService.canLogin(mail, password)) {
            session.setAttribute("username", mail);
            
            User u = userService.getByEmail(mail);
            session.setAttribute("userId", u.getId());
            session.setAttribute("firstName", u.getFirstName());
            session.setAttribute("lastName", u.getLastName());
            resp.sendRedirect(req.getServletContext().getContextPath() + "/");
        }
        else {
            req.setAttribute("message", "Adresse mail / mot de passe invalide");
            RequestDispatcher rd = req.getRequestDispatcher("/jsp/login.jsp");
            rd.forward(req, resp);
        }
             
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        RequestDispatcher rd = req.getRequestDispatcher("/jsp/login.jsp");
        rd.forward(req, resp);
    }
}
